<?php

namespace App\Helper;

class RSAHelper
{
    // 解密
    static public function decrypt($content)
    {
        // $private_key = file_get_contents('key/rsa_private_key.pem');
        // $pi_key =  openssl_pkey_get_private($private_key);//这个函数可用来判断私钥是否是可用的，可用返回资源id Resource id
        // $decrypted = "";
        // openssl_private_decrypt(base64_decode($data),$decrypted,$pi_key);//私钥解密

        // return $decrypted;

        $priKey = file_get_contents('key/rsa_private_key.pem');
        $res = openssl_get_privatekey($priKey);
        //用base64将内容还原成二进制
        $content = base64_decode($content);
        //把需要解密的内容，按128位拆开解密
        $result  = '';
        for($i = 0; $i < strlen($content)/128; $i++  ) {
            $data = substr($content, $i * 128, 128);
            openssl_private_decrypt($data, $decrypt, $res);
            $result .= $decrypt;
        }
        openssl_free_key($res);

        return $result;
    }

    // 加密
    static public function encrypt($data)
    {
        $encrypted = '';
        $public_key = file_get_contents('key/rsa_public_key.pem');
        $pu_key = openssl_pkey_get_public($public_key);
        openssl_public_encrypt($data, $encrypted, $pu_key);//公钥加密
        $encrypted = base64_encode($encrypted);// base64传输
        return $encrypted;
    }
}